package com.tskj.leonsu.service;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.tskj.leonsu.aop.annotation.SystemControllerLog;
import com.tskj.leonsu.dao.BathRoomDAO;
import com.tskj.leonsu.utility.Tools;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.support.DefaultTransactionDefinition;
import org.springframework.web.bind.annotation.RequestBody;

import javax.annotation.Resource;

/**
 * @author LeonSu
 */
@Service
public class BathRoomService {

    @Autowired
    private ThreadPoolTaskExecutor bathThreadPoolTaskExecutor;

    //预约开始时间
    private final String START_TIME = "08:00:00";

    //预约结束时间
    private final String END_TIME = "23:59:59";

    @Autowired
    private BathRoomDAO bathRoomDAO;

    public JSONArray getBathRoomList(String sex) {
        return bathRoomDAO.getBathRoomList(sex);
    }

    public String getBathRoomId(String bathRoomName) {
        return bathRoomDAO.getBathRoomId(bathRoomName);
    }

    public JSONArray getTimeAndCountList(String bathId, String date) {
        JSONArray allList = bathRoomDAO.getTimeAndCountList(bathId, date);
        JSONArray retArray = new JSONArray();
        JSONObject data;
        String currentTime = Tools.getNewDateTime();
        for (Object obj : allList) {
            JSONObject json = (JSONObject) obj;
            if (String.format("%s %s", date, json.getString("endtime")).compareToIgnoreCase(currentTime) <= 0) {
//            if (json.getString("endtime").compareToIgnoreCase(currentTime) <= 0) {
                continue;
            }

            data = new JSONObject();
            data.put("id", json.getString("tid"));
            data.put("timeTitle", String.format("%s - %s", Tools.getShortTime(json.getString("starttime")), Tools.getShortTime(json.getString("endtime"))));
            data.put("timeCount", json.getIntValue("bnum"));
            retArray.add(data);
        }
        return retArray;
    }

    /**
     * 判断当前时间是否在可预约的时间范围内
     *
     * @return true：是在时间范围内，false：不在时间范围内
     */
    public boolean isValidSubscribeTime() {
        return true;
//        String time = Tools.getNowTime();
//        if (Tools.today().equals("2020-05-07")) {
//            return true;
//        } else {
//            return (time.compareTo(START_TIME) >= 0 && time.compareTo(END_TIME) <= 0);
//        }
    }

    @Resource(name = "transactionManager")
    private DataSourceTransactionManager transactionManager;

    @SystemControllerLog(MODULENAME = "洗浴")
    @Transactional(rollbackFor = Exception.class)
    public JSONObject saveOrder(JSONObject student, JSONObject data) {
        JSONObject retData = new JSONObject();

        //TODO：保存前，需要检查当前时间是否在08：00-23：59范围内
        if (!isValidSubscribeTime()) {
            retData.put("code", 1);
            retData.put("errMsg", "未到预约时间，不能创建订单");
            return retData;
        }

//        DefaultTransactionDefinition transDefinition = new DefaultTransactionDefinition();
        //开启新事物
//        transDefinition.setPropagationBehavior(DefaultTransactionDefinition.PROPAGATION_REQUIRES_NEW);
//        TransactionStatus transStatus = transactionManager.getTransaction(transDefinition);
        try {
            String timeId = data.getString("id");
            String bathRoom = data.getString("bathRoom");
            String bathId = data.getString("bathId");
            String newBathId = bathRoomDAO.getBathRoomId(bathRoom);
            if (!newBathId.equalsIgnoreCase(bathId)) {
                retData.put("code", 1);
                retData.put("errMsg", "数据不正确");
//                transactionManager.rollback(transStatus);
                return retData;
            }
            String dateString = data.getString("date");
            String timeString = data.getString("time");
            String startTime = timeString.split("-")[0].trim();
            String endTime = timeString.split("-")[1].trim();

            String currentTime = Tools.getNewDateTime();
            if (String.format("%s %s:00", dateString, endTime).compareToIgnoreCase(currentTime) <= 0) {
                retData.put("code", 1);
                retData.put("errMsg", "超过预约截止时间，不能创建订单，请另选时间！！！");
//                transactionManager.rollback(transStatus);
                return retData;
            }

            String adUserName = student.getString("username");
            //TODO：保存前，需要检查当前用户是否已有未完成订单
            if (bathRoomDAO.hasOrder(adUserName, dateString)) {
                retData.put("code", 1);
                retData.put("errMsg", "已创建过订单，请不要重复创建");
//                transactionManager.rollback(transStatus);
                return retData;
            }

            //TODO:保存前，需要检查当前时间是否已订满
            if (!bathRoomDAO.canSave(bathRoom, startTime, endTime, 0, dateString)) {
                retData.put("code", 1);
                retData.put("errMsg", "当前时间已订满，请选择其他时间");
//                transactionManager.rollback(transStatus);
                return retData;
            }

            String sex = student.getString("sexy");
            int sexId = sex.equals("男") ? 1 : 0;
            String studentName = student.getString("studentname");
            String studentNo = student.getString("studentid");
            String xueYuan = student.getString("xueyuan");
            String bathSortNo = bathRoomDAO.getBathSortNo(bathId, bathRoom);
            String timeSortNo = bathRoomDAO.getTimeSortNo(bathId, timeId);
            String maxOrderNo = bathRoomDAO.getMaxOrderNo(bathRoom, dateString, startTime, endTime);
            String code = String.format("%s-%s-%d%03d", bathSortNo, timeSortNo, sexId, Integer.valueOf(maxOrderNo));

            bathRoomDAO.save(Tools.newId(), studentName, sex, xueYuan, Integer.valueOf(maxOrderNo), bathRoom, startTime, endTime, 0, code, dateString, adUserName);
            retData.put("code", 0);
            JSONObject detail = new JSONObject();
            retData.put("data", detail);
            student = new JSONObject();
            student.put("name", studentName);
            student.put("no", studentNo);
            student.put("sex", sex);
            student.put("xueYuan", xueYuan);
            detail.put("student", student);

            JSONObject order = new JSONObject();
            order.put("type", 1);
            order.put("address", bathRoom);
            order.put("date", dateString);
            order.put("time", timeString);
            order.put("code", code);

            detail.put("order", order);
//            transactionManager.commit(transStatus);
            return retData;
        } catch (Exception e) {
            e.printStackTrace();
            retData.put("code", 1);
            retData.put("errMsg", "洗浴订单创建失败，请稍后重试");
//            transactionManager.rollback(transStatus);
            return retData;
        }
    }

    /**
     * 检查是否允许下订单，一是：8:00-16:00能下，二是如果该用户没有下过明天的订单
     *
     * @param userName
     * @param date
     * @return
     */
    public JSONObject checkStopTime(String userName, String date) {
        JSONObject ret = new JSONObject();
        ret.put("code", 0);
        String time = Tools.getNowTime();
        JSONObject setTimes = bathRoomDAO.getStartTime();
        if (time.compareTo(setTimes.getString("start")) < 0 || time.compareTo(setTimes.getString("end")) > 0) {
            ret.put("data", false);
            ret.put("start", setTimes.getString("start"));
            ret.put("end", setTimes.getString("end"));
        } else {
            ret.put("data", true);
            if (bathRoomDAO.getOrderByAdUserName(userName, date) > 0) {
                ret.put("data", false);
            }
        }
        return ret;
    }

    public JSONArray getUnFinishedOrder(String adUserName) {
        return bathRoomDAO.getUnFinishedOrder(adUserName);
    }

    public JSONArray getFinishedOrder(String adUserName) {
        return bathRoomDAO.getFinishedOrder(adUserName);
    }

    public JSONArray getAllOrder(String adUserName) {
        return bathRoomDAO.getAllOrder(adUserName);
    }

    public void confirmOrder(String adUserName, String id) throws Exception {
        if (bathRoomDAO.getCanConfirm(id)) {
            bathRoomDAO.confirmOrder(adUserName, id);
        } else {
            throw new Exception("订单确认失败，未到允许订单确认时间");
        }
    }

    public void cancelOrder(String adUserName, String id) throws Exception {
        if (bathRoomDAO.getCanCancel(id)) {
            bathRoomDAO.cancelOrder(adUserName, id);
        } else {
            throw new Exception("订单取消失败，超过订单取消时间");
        }
    }
}
